package pers.csw.lookBook.controller.front;

import cn.dev33.satoken.annotation.SaCheckLogin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import pers.csw.lookBook.common.Res;
import pers.csw.lookBook.entity.Comment;
import pers.csw.lookBook.entity.GiveLike;
import pers.csw.lookBook.server.WebSocketServer;
import pers.csw.lookBook.service.CommentService;
import pers.csw.lookBook.service.GiveLikeService;
import pers.csw.lookBook.service.RedisService;
import pers.csw.lookBook.utils.RedisKeyUtils;
import pers.csw.lookBook.vo.GiveLikeVo;

import java.io.IOException;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/giveLike")
public class GiveLikeController {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    RedisService redisService;
    @Autowired
    GiveLikeService giveLikeService;
    @Autowired
    CommentService commentService;

    @SaCheckLogin
    @RequestMapping("/redisGiveLike/{userId}/{pId}")
    public Boolean redisGiveLike(@PathVariable Integer userId, @PathVariable Integer pId){
        Comment byId = commentService.getById(pId);
        if(byId!=null){
            try {
                WebSocketServer.sendInfo("您有一条新的信息!",String.valueOf(byId.getUid()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String key = RedisKeyUtils.getLikedKey(userId,pId);
        String value = (String) redisTemplate.opsForHash().get(RedisKeyUtils.MAP_KEY_USER_LIKED, key);
        if(value!=null){
            if(value.equals("1")) {
                redisService.unlikeFromRedis(key);
                redisService.decrementLikedCount(String.valueOf(pId));
                return false;
            }else{
                redisService.saveLiked2Redis(key);
                redisService.incrementLikedCount(String.valueOf(pId));
                return true;
            }
        }else{
            GiveLike giveLike = giveLikeService.getGiveLike(userId, pId);
            if(giveLike!=null&&giveLike.getStatue()==1){
                redisService.unlikeFromRedis(key);
                String o = (String) redisTemplate.opsForHash().get(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT, pId);
                if(Integer.valueOf(o)>0 && o!=null){
                    redisService.decrementLikedCount(String.valueOf(pId));
                }
            }else{
                redisTemplate.opsForHash().put(RedisKeyUtils.MAP_KEY_USER_LIKED, key, "1");
                redisService.incrementLikedCount(String.valueOf(pId));
            }
            return true;
        }
    }

    @GetMapping("/getUserLike/{userId}")
    public Res getUserLike(@PathVariable Integer userId){
        List<GiveLikeVo> userLike = giveLikeService.getUserLike(userId);
        return Res.success(userLike);
    }
}
